#!/bin/bash
#THIS DRIVER WRITTEN BY MATTHEW VONA ARB FOR THE PICARRO ULTRASONIC ANEMOMETER
#FOR QUESTIONS WRITE mailto:mvona@arb.ca.gov
#TRAP CTRL+C
trap cleanup 1 2 3 6 15
# THIS IS THE FUNCTION CALLED IN THE EVENT THAT CTRL+C IS PRESSED
DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

#COMMAND TO RUN WHEN WANTING TO REMOVE ALL SUB-SECOND FILES
clean_temp_data()
{
	:
}
#COMMAND TO RUN PRIOR TO DATA COLLECTION TO ENSURE THAT NO OLD DATA EXISTS
pre_run()
{
	clean_temp_data
	#set_config
	:
}
pre_run


#INITIALIZE THE RMYOUNG PICARRO RECORDER
record()
{
	bash ${DIR}/rmcord "${dvc_prt}" "${bd_rt}"&
	rm_id="$!"
	if [ -z "$rm_id" ]
		then 
			echo "Failed to start the Picarro http recorder."
	fi
}
#GET RID OF EXTRA DATA FILES
cleanup()
{
	echo "Caught Signal ... cleaning up."
		if !(rm -f Data/.locked > /dev/null); then
       			{
               		 exit 1
			
        		} 
		fi
	kill ${rm_id}	
	clean_temp_data 

	echo "Done cleanup ... quitting."
	exit 1
}
#COMMAND TO RUN TO ENSURE THAT THE SETTINGS ARE CORRECT FOR THIS DRIVER
set_config()
{
	:

}

#COMMAND TO 
#BEGIN WRITE
#THIS FUNCTION HANDELS READ RIGHT HANDSHAKES BETWEEN VARIOUS DRIVERS
#IN GENERAL, THE DATA IS PLACED IN THE VARIABLE $TIMESTAMP PRIOR TO CALL
#NEXT, IT OPENS THE DATA DIRECTORY AND LOOKS FOR THE .locked FILE
#IF IT EXISTS, IT HANGS OUT UNTIL IT DOESN'T EXIST. AT THAT POINT
#IT CREATES A .locked FILE, AND APPENDS TO THE DATA RECORD.
#FINALLY IT REMOVES THE .locked FILE IT HAS CREATED.
#THIS FUNCTION ALSO PARSES THE .DISABLED FILE IN THE DRIVER FOLDER
#AND TAKES A CHANNEL OFF LINE BY PREPENDING --DISABLED-- TO EACH LINE OF CONTENT IN THE DATA DIRECTORY
#written by MJV
write()
{
#CONFIRM THAT THERE IS NO HIDDEN FILE CALLED '.locked'
	while [ -e "Data/.locked" ];
		do
			sleep .2;
		done	
	echo "LOCKED" > "Data/.locked";
	#PARSE THE .disabled File
	channel_status=`cat "$DIR/.disabled${instance}"`
	#IF THE FILE DOSEN'T EXIT OR IS NOT ACCESIBLE
	#MAKES SURE A VALUE OF 0 IS USED
	if [ `expr $channel_status + 0` -eq 1 ]; then
		if !(echo "$data" | sed 's/^/'$timestamp'/g'| sed 's/$/'\-\-DISABLED\-\-'/g' >> "Data/$datafile" ); then
			{
			echo "GENERAL FAILURE WRITING TO RECORD: $#";
			cleanup;
			}
		fi
	else
		if !(echo "$data" | sed 's/^/'$timestamp'/g' >> -a "Data/$datafile"); then
			{
			echo "GENERAL FAILURE WRITING TO RECORD: $#";
			cleanup;
			}
		fi
	
	fi
	if !(rm -f "Data/.locked" > /dev/null); then
		{
			echo "GENERAL FAILURE REMOVING LOCK: $#";
			exit 1;	
		}
	fi
	if !(timestamp="" && data=""); then
		{
		echo "GENERAL FAILURE CLEARING WRITE BUFFER: $#";
		cleanup;
		}
	fi	
}
	
#THIS IS THE ACTUAL COMMUNICATION WITH THE INSTRUMENT
#THE TIMER CONTROL. AT THE BEGINING IT TESTS FOR THE 
#EXISTENCE IF TOGGLE VARRIABLES WHICH ARE UTILIZED BOTH BY
#THE COMM ROUTINE runit() AND THE DIAGNOSTICS DATA ROUTINE
#diag()

#THIS IS THE FUNCTION RUN IN THE EVENT THAT THE REQUIRED PARAMETERS
#ARE NOT ENTERED.
usage()
{
clear
cat << EOF
usage: $0 options
OPTIONS:

-r	rprt_nm [rn]
-d	dvc_prt [eg, /dev/ttyS0, /dev/ttyUSB1] 
-b	bd_rt [2400,4800,9600,38400etc.]
-s	SAROAD number of the station

Last updated 1/26/2011
EOF
}
#HELP FUNCTION GIVES BACKGROUND ON THIS DRIVER
help_me ()
{
clear
cat .help
exit 0
}
def_opts ()
{
clear
cat .options
}

##CLEAR ALL VARIABLES               
rprt_nm= ; dvc_prt="146.114.111.121" ; bd_rt=50120 ; cmnd1= ; wt_rsp1= ; bd_rt= ; rsp_lngth= ; izs_val= ;
dvc_prt= ; frqncy= ; dtr= ; ctr= ; p8n1= ; izs= ; saroad= ; p8n1= ; id_nmbr= ; instance=1
##INITIALIZE THE BUFFER
## return='NOT WRITTEN TO'
##loop through all variables and parameters
##Note that the position of the colon indicates the presence
##of a parameter to collect. The h parameter simply
##returns the help message.

while getopts “hr:s:d:b:I:” OPTION
do
case $OPTION in
s)
saroad=$OPTARG
;;
r)
rprt_nm=$OPTARG
;;
d)
dvc_prt=$OPTARG
;;
b)
bd_rt=$OPTARG
;;
h)
usage
exit 1
;;
I)
instance=$OPTARG
;;
*)
usage
exit 1
;;
esac
done
#CHECK FOR THE CRITICAL PARAMETERS, IF THEY ARE NOT PRESENT THEN
#RUN THE USAGE FUNCTION WHICH RETURNS THE INSTRUCTIONS FOR PROPER USAGE
#MUST HAVE r n d b s
if [ -z "$rprt_nm" ] || [ -z "$dvc_prt" ] || [ -z "$bd_rt" ] || [ -z "$saroad" ]
	then
		{
		usage
		exit
		}
fi
	#INITIALIZED THE RAN VARIABLE. THIS IS USED TO TOGGLE THE TIMER GATE
ran=0
record || exit
#start the 81000
#SETUP THE OPERATING LOOP
while :
do
	hour=`date "+%H"`
	minute=`date "+%M"`
	second=`date "+%S"`
	if [ "$second" -eq "01" ] && [ "$ran" -eq "0" ]; then
	{
	#"Oct 9, 2014"
		bash ${DIR}/parse.sh `date -d "5 minutes ago" '+%Y-%m-%d %H:%M'` "DMS" "Picarro" >> ${DIR}/.to_dms
		bash ${DIR}/parse.sh `date -d "5 minutes ago" '+%Y-%m-%d %H:%M'` "CL" "Picarro" >>/home/aqdms/CARBLog/Data/${saroad}-`date '+%Y-%d-%m'`
		ran=1	
	
		sleep 1
		if [ "$minute" -eq "59" ]; then
		{
		  cat ${DIR}/.to_dms | sed 's/$/\r/' >> ${saroad}-`date '+%Y-%d-%m-%H-%M_P.MIN'`
		  cat /dev/null > ${DIR}/.to_dms
		
			#run maintenance on the .write_cache file nightly
			if [ "$hour" -eq "23" ]; then
			{
				bash /home/aqdms/CARBLog/resources/Picarro_drv/trim_write_cache.sh
			}
			fi
		}
		fi


	}
	#AND WAIT ONE SECOND BEFORE CHECKING AGAIN
	else 
	{
		#PERFORM MAINTENANCE ON THE WRITE CACHE
		
		if [ "$second" -eq "15" ] && [ "$minute" -eq "30" ] && [ "$hour" -eq "07" ]; then
		{
			#remove any garbage that may have gotten in there
			#normally this will not be processed, but let's clean it out
			sed -i ':v/^20[1-9][0-9]-/d' ${DIR}/.write_cache
			#REMOVE ANY DUPLICATE LINES THAT MAY HAVE RESULTED FROM BACKPOLLING
			cat ${DIR}/.write_cache | sort -u > ${DIR}/.write_cache_temp
			mv ${DIR}/.write_cache_temp ${DIR}/.write_cache	
			
		}
		fi
		
		#WAIT ONE SECOND
			sleep .5
		#SET RAN TO 0
			ran=0
	}
	fi
done;
exit;


